<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>

<body>
    <h1>调用C# DLL示例</h1>
    <div>
        <label for="param1">参数1：</label>
        <input type="text" id="param1" />
    </div>
    <br />
    <div>
        <label for="param2">参数2：</label>
        <input type="text" id="param2" />
    </div>
    <br />
    <div>
        <label for="result">结&nbsp;&nbsp;果：</label>
        <input type="text" id="result" readonly />
    </div>
    <br />
    <div>
        <button onclick="calculate()">计算</button>
    </div>
    <br />

    <div>
        <iframe id="inner" src="inner.html" frameborder="1" onload="callSayHi()"></iframe>
    </div>

    <script>
        // 初始化绑定js对象容器
        async function init() {
            await CefSharp.BindObjectAsync("methodInvoker");
        }

        init();

        function calculate() {
            const param1 = document.getElementById("param1").value.trim();
            const param2 = document.getElementById("param2").value.trim();
            if (!(/^-?\d+(\.\d+)?$/.test(param1))) {
                alert("参数1必须为数字");
                return;
            } else if (!(/^-?\d+(\.\d+)?$/.test(param2))) {
                alert("参数2必须为数字");
                return;
            }

            const request = {
                dllPath: "Calculator.dll",
                nameSpace: "Calculator",
                className: "Calculator",
                methodName: "Add",
                parameters: [Number(param1), Number(param2)]
            };

            // 通过中介对象调用C#，这里方法名首字母要小写
            methodInvoker.invokeMethod(JSON.stringify(request))
                .then((result) => {
                    const response = JSON.parse(result);
                    if (response.success) {
                        document.getElementById("result").value = response.result;
                    } else {
                        alert(`错误：${response.error}`);
                    }
                });
        }

        function callSayHi() {
            const inner = document.getElementById("inner");
            const result = document.getElementById("result");
            try {
                if (inner.contentWindow && inner.contentWindow.sayHi) {
                    result.value = inner.contentWindow.sayHi();
                }
            } catch (error) {
                result.value = error.toString();
            }
        }
    </script>
</body>

</html>